package com.epcs.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailHandler implements Runnable {

	private String toAddress;
	private String mailSubject;
	private String fromAddress = "hahaidangvietnam@gmail.com";
	private String content;
	private String username = "hahaidangvietnam@gmail.com";
	private String password = "Yahoo 1992";

	public void sendEMail(String email, String content, String mailSubject) {
		this.toAddress = email;
		this.content = content;
		this.mailSubject = mailSubject;
		System.out.println(email);
	}

	@Override
	public void run() {
		Properties properties = new Properties();
        // set properties
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.socketFactory.port", "465");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", "465");
        Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username,password);
            }
        });

		try {
		if(toAddress != null){
		
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(fromAddress));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
			message.setSubject(mailSubject);
			message.setContent(content,"text/html; charset=utf-8");
			Transport.send(message);
			System.out.println("Mail sending Process is Done");
		
		}
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}

	}

	//cách xài
	/**
	 * // send mail
			MailHandler mail = new MailHandler();
			String link = "http://epcs.com:8080/EPCS" + thay bằng link tới event đó; nếu xài cái gì có link thì ghi thế này
			mail.sendEMail(email, nội dung, tiêu đề);
			Thread thread = new Thread(mail);
			thread.start();
			System.out.println("Verified Mail has been sent!");

	 */
	
}
